package dto

import (
	"oss-api/app/model"
	"oss-api/boot"
	"oss-api/library/request"
	"oss-api/library/response"
	"oss-api/library/utils"
	"time"
)

var Category = new(CategoryDto)

type CategoryDto struct{}

// FindByCateId 通过ID查找分类
func (c *CategoryDto) FindByCateId(cateId int64) (model.Category, error) {
	var (
		data model.Category
		err  error
	)
	err = boot.DB.
		Where("can_view = true and id = ?", cateId).
		Take(&data).Error
	if err != nil {
		return model.Category{}, err
	}
	return data, nil
}

// FindAll 获取所有分类
func (c *CategoryDto) FindAll() ([]response.CategorySimpleVo, error) {
	var data []response.CategorySimpleVo
	err := boot.DB.Model(&model.Category{}).
		Where("can_view = true").
		Find(&data).
		Error
	if err != nil {
		return nil, err
	}
	return data, nil
}

// Save 增加
func (c *CategoryDto) Save(params request.CreateCategoryVo) (model.Category, error) {
	var (
		category model.Category
		err      error
	)
	err = utils.StructCopy(params, &category)
	if err != nil {
		return model.Category{}, nil
	}
	category.CanView = true
	category.CreatedTime = time.Now()
	category.UpdatedTime = time.Now()
	category.Id = boot.IdBuilder.NextId()
	if err = boot.DB.Create(&category).Error; err != nil {
		return model.Category{}, err
	}
	return category, nil
}

// FindCondition 条件查询
func (c *CategoryDto) FindCondition(query interface{}, args ...interface{}) ([]response.CategorySimpleVo, error) {
	var result []response.CategorySimpleVo
	if err := boot.DB.Model(&model.Category{}).Where(query, args).Find(&result).Error; err != nil {
		return []response.CategorySimpleVo{}, err
	}
	return result, nil
}
